package com.tony.demo.test.swipe_coordinator;

import android.util.SparseArray;

import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.appbar.AppBarLayout;
import com.tony.demo.R;
import com.tony.demo.mvp.presenter.impl.BasePresenter;
import com.tony.demo.test.swipe_coordinator.adapter.ImgPagerAdapter;
import com.tony.demo.test.swipe_coordinator.adapter.NewsAdapter;
import com.tony.demo.test.swipe_coordinator.adapter.UnderLineNavigatorAdapter;
import com.tony.demo.test.swipe_coordinator.bean.TagBean;
import com.tony.demo.test.swipe_coordinator.view.DividerItemDecoration;
import com.tony.demo.ui.base.BaseActivity;
import com.tony.demo.ui.framework.FrameworkFragment;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.ArrayList;
import java.util.List;

public class SwipeRefreshCoordinatorActivity extends BaseActivity
        implements AppBarLayout.OnOffsetChangedListener {

    private MagicIndicator channelIndicator;
    private ViewPager vpList;


    private ImgPagerAdapter imgPagerAdapter = null;
    private PagerAdapter listPagerAdapter = null;
    private int[] imgList = new int[]{R.mipmap.timg, R.mipmap.timg2, R.mipmap.timg2};
    private List<TagBean> tagList = new ArrayList<>();
    private SparseArray<RecyclerView> viewSparseArray = new SparseArray<>();
    private UnderLineNavigatorAdapter indicatorAdapter;
    private boolean isRefresh = false;
    private List<String> mList = new ArrayList<>();

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int getViewLayout() {
//        setContentView(R.layout.activity_swipe_refresh_coordinator);
        return R.layout.activity_swipe_refresh_coordinator;
    }

    public void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        ViewPager imgViewpager = findViewById(R.id.img_viewpager);
        AppBarLayout barLayout = findViewById(R.id.bar_layout);
        channelIndicator = findViewById(R.id.vp_indicator);
        vpList = findViewById(R.id.vp_list);

        toolbar.setTitle("Test");
        tagList.add(new TagBean(0, "推荐"));
        tagList.add(new TagBean(1, "财经"));
        tagList.add(new TagBean(2, "娱乐"));
        tagList.add(new TagBean(3, "体育"));
        tagList.add(new TagBean(4, "情感"));

        imgPagerAdapter = new ImgPagerAdapter(this, imgList);
        imgViewpager.setAdapter(imgPagerAdapter);

        barLayout.addOnOffsetChangedListener(this);

        List<Fragment> mFragments = new ArrayList<>();
        FrameworkFragment first = new FrameworkFragment();
        mFragments.add(first);
        mFragments.add(new FrameworkFragment());
        mFragments.add(new FrameworkFragment());
        mFragments.add(new FrameworkFragment());
        mFragments.add(new FrameworkFragment());
        SimpleFragmentPagerAdapter mAdapter =
                new SimpleFragmentPagerAdapter(getSupportFragmentManager(), mFragments);
        vpList.setAdapter(mAdapter);  //给ViewPager设置适配器
        vpList.setOffscreenPageLimit(1);  //预加载两个。这样在切换fragment时，第一个或第三个fragment就不会重新加载了

        initVPIndicator();
    }

    public class SimpleFragmentPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> listFragments;

        public SimpleFragmentPagerAdapter(FragmentManager fm, List<Fragment> al) {
            super(fm);
            listFragments = al;
        }

        @Override
        public Fragment getItem(int position) {
            return listFragments.get(position);
        }

        @Override
        public int getCount() {
            return listFragments.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return super.getItemPosition(object);
        }
    }

    private void initVPIndicator() {
        final CommonNavigator commonNavigator = new CommonNavigator(this);
        indicatorAdapter = new UnderLineNavigatorAdapter(this, tagList);
        indicatorAdapter.setRelateViewPager(vpList);
        commonNavigator.setAdapter(indicatorAdapter);
        channelIndicator.setNavigator(commonNavigator);
        vpList.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                channelIndicator.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                endLoadEverything();
                channelIndicator.onPageSelected(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                channelIndicator.onPageScrollStateChanged(state);
                if (state == ViewPager.SCROLL_STATE_IDLE) {

                }
            }
        });
    }

    private RecyclerView getView(int tagId) {
        RecyclerView recyclerView = viewSparseArray.get(tagId, null);
        if (null == recyclerView) {
            recyclerView = generateView(tagId);
        }
        return recyclerView;
    }

    private RecyclerView generateView(int tagId) {
        RecyclerView recyclerView = new RecyclerView(this);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        DividerItemDecoration itemDecoration = new DividerItemDecoration(this, LinearLayoutManager.VERTICAL);
        recyclerView.addItemDecoration(itemDecoration);
        NewsAdapter adapter = new NewsAdapter(this);
        recyclerView.setAdapter(adapter);
        viewSparseArray.put(tagId, recyclerView);
        return recyclerView;
    }

    /**
     * 拉取数据
     *
     * @param tagId
     */
    private void getData(int tagId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (Exception e) {

                }

            }
        }).start();
        Integer tag = (Integer) getView(tagId).getTag();
        NewsAdapter adapter = (NewsAdapter) getView(tagId).getAdapter();
        if (null == tag || tag == 0) {
            tag = 1;
        }
        endLoadEverything();
        if (isRefresh) {
            tag = 1;
            adapter.updateItems(createData(tagId, tag));
            isRefresh = false;
        } else {
            adapter.addItems(createData(tagId, tag));
        }
        getView(tagId).setTag(++tag);

    }

    /**
     * 造数据 默认每页20条
     *
     * @param pageIdx
     * @return
     */
    private List<String> createData(int tagId, int pageIdx) {
        String str = tagList.get(tagId).getTagName() + "界面 ";
        List<String> list = new ArrayList<>();
        int i = (pageIdx - 1) * 20;
        for (; i < pageIdx * 20; i++) {
            list.add(str + i);
        }
        return list;
    }


    private void endLoadEverything() {
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        if (tagList == null) {
            return;
        }
    }

    public boolean isTop() {
        int tagId = tagList.get(vpList.getCurrentItem()).getTagId();
        return !(getView(tagId)).canScrollVertically(-1);
    }

    public boolean isBottom() {
        int tagId = tagList.get(vpList.getCurrentItem()).getTagId();
        return !(getView(tagId)).canScrollVertically(1);
    }

    public static boolean isVisBottom(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //屏幕中最后一个可见子项的position
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //当前屏幕所看到的子项个数
        int visibleItemCount = layoutManager.getChildCount();
        //当前RecyclerView的所有子项个数
        int totalItemCount = layoutManager.getItemCount();
        //RecyclerView的滑动状态
        int state = recyclerView.getScrollState();
        if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean isSlideToBottom(RecyclerView recyclerView) {
        if (recyclerView == null) return false;
        if (recyclerView.computeVerticalScrollExtent() + recyclerView.computeVerticalScrollOffset()
                >= recyclerView.computeVerticalScrollRange())
            return true;
        return false;
    }
}
